﻿///***************************************************************
/// 시  스  템 : Updms.Prj
/// 단위시스템 : PRJ
/// 계      층 : Presentation Layer
/// 프로그램명 : Prj4010b
/// 파  일  명 : Prj4010b.aspx.cs
/// 설      명 : 프로젝트진척업로드
///***************************************************************
/// 수정ID 일자       이름     내용
///---------------------------------------------------------------
/// CH001  2008-12-22 송시명   최초 작성
///***************************************************************
using System;
using System.Data;
using System.Data.OleDb;
using System.IO;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;

using SMFramework.Utility;

using Base.AppFramework;
using Base.AppFramework.Web.UI.CommandBar;
using Base.Dac;

using Updms.Prj.Exe;


namespace Updms.Prj
{
	public partial class Prj4010b : Updms.Common.BaseClass.PageBase
	{
		#region 전역영역

		//프로그램상수
		public static readonly string PID = "Prj4010b";

		Global global = new Global();
		AccessCheck access = new AccessCheck();

		// 페이지모드
		private string gs_page_mode = "";

		OleDbConnection con;
		protected string gs_source = FILE_PATH_UPLOAD_EXCEL_BATCH + PID + "_template.xls"; 

		#endregion

		#region Page_Load

		protected void Page_Load(object sender, EventArgs e)
		{
			if (!Page.IsPostBack)
			{
				//최초 화면 로딩시 처리해야 할 부분
				SetLiterals(global.GetLabelInfoByPgmId(PID, LANG_SET));
			}
		}

		#endregion

		#region InitializeComponent

		private void InitializeComponent()
		{
			this.Load += new System.EventHandler(this.Page_Load);
			this.PreRender += new System.EventHandler(this.Page_PreRender);
		}

		#endregion		

		#region ShowKeywordLabel
		
		//검색키워드
		private void ShowKeywordLabel()
		{
			lbl_search_keyword.Text = PID + "_template.xls";
		}

		#endregion

		#region CRUD (SelectProcess, InsertProcess, SearchProcess)

		//조회
		private void SelectProcess()
		{
			DataSet lo_ds = new DataSet();
			OleDbDataAdapter adapter;

			if (FileUtil.IsFileExist(gs_source))
			{
				try
				{
					string connStr = @"provider=Microsoft.ACE.OLEDB.12.0;data source=" + gs_source + ";Extended Properties=Excel 12.0;";
					con = new OleDbConnection(connStr);
					con.Open();

					string query = "SELECT * FROM [Sheet1$]";

					adapter = new OleDbDataAdapter(query, con);
					lo_ds = new DataSet();

					adapter.Fill(lo_ds, "UPDMS_PRJ_PROGRESS_MGT");

					gs_page_mode = DataSetUtil.CheckRowCount(lo_ds, "UPDMS_PRJ_PROGRESS_MGT") ? "R" : "N";
					
					GridView1.DataSource = lo_ds;
					GridView1.DataBind();

					ShowKeywordLabel();
					lbl_result_count.Text = DataSetUtil.GetRowCount(lo_ds, "UPDMS_PRJ_PROGRESS_MGT").ToString();
				}
				catch (OleDbException oe)
				{
					SMEventLog.WriteExceptionLog(oe);
				}
				catch (Exception e)
				{
					SMEventLog.WriteExceptionLog(e);
				}
				finally
				{
					con.Close();
				}
			}
			else
			{
				CallMsgBoxInAjax("MSG_ERR_126");	// 템플릿 파일이 없습니다
			}
		}

		//저장
		private void InsertProcess()
		{
			using (Prj4010b_RT _Prj4010b_RT = new Prj4010b_RT())
			{
				int li_return = _Prj4010b_RT.InsertProcess(SetValue());
				string ls_msg_id = (li_return > 0) ? "MSG_INF_007" : "MSG_ERR_105";	//저장되었습니다:저장할 수 없습니다
				CallMsgBoxInAjax(ls_msg_id);
			}
		}

		//검색
		private void SearchProcess()
		{
			SelectProcess();
		}

		#endregion

		#region CheckData, SetValue

		//체크
		private bool CheckData()
		{
			bool lb_rslt = true;
			//공통코드를 배열에 담아둔다
			DataSet lo_ds = new DataSet();
			lo_ds.Merge(global.GetCommCd("PRJ", "", LANG_SET));
			string[] la_cd = DataSetUtil.GetArrayFromDataSet(lo_ds, "UPDMS_COM_CD", "Value");

			for (int i = 0; i < GridView1.Rows.Count; i++)
			{
				GridViewRow row = GridView1.Rows[i];
				HtmlInputCheckBox cb = (HtmlInputCheckBox)row.FindControl("cb_check");

				if (cb.Checked)
				{
					string ls_prj_id			= ConversionUtil.DefaultValue(GridView1.Rows[i].Cells[2].Text);
					string ls_reg_dt			= ConversionUtil.DefaultValue(GridView1.Rows[i].Cells[3].Text);
					string ls_work_tp			= ConversionUtil.DefaultValue(GridView1.Rows[i].Cells[4].Text);
					string ls_pgm_nm			= ConversionUtil.DefaultValue(GridView1.Rows[i].Cells[5].Text);
					string ls_div				= ConversionUtil.DefaultValue(GridView1.Rows[i].Cells[6].Text);
					string ls_no				= ConversionUtil.DefaultValue(GridView1.Rows[i].Cells[7].Text);
					string ls_title				= ConversionUtil.DefaultValue(GridView1.Rows[i].Cells[8].Text);
					string ls_contents			= ConversionUtil.DefaultValue(GridView1.Rows[i].Cells[9].Text);
					string ls_handle_contents	= ConversionUtil.DefaultValue(GridView1.Rows[i].Cells[10].Text);
					string ls_concern_person	= ConversionUtil.DefaultValue(GridView1.Rows[i].Cells[11].Text);
					string ls_handle_time		= ConversionUtil.DefaultValue(GridView1.Rows[i].Cells[12].Text);
					string ls_receive_dt		= ConversionUtil.DefaultValue(GridView1.Rows[i].Cells[13].Text);
					string ls_complete_dt		= ConversionUtil.DefaultValue(GridView1.Rows[i].Cells[14].Text);
					string ls_real_complete_dt	= ConversionUtil.DefaultValue(GridView1.Rows[i].Cells[15].Text);
					string ls_status			= ConversionUtil.DefaultValue(GridView1.Rows[i].Cells[16].Text);
					string ls_remark			= ConversionUtil.DefaultValue(GridView1.Rows[i].Cells[17].Text);
					
					//빈값체크
					if (ls_prj_id == "-" || ls_reg_dt == "-" || ls_pgm_nm == "-" ||
						ls_no == "0" || ls_title == "-" || ls_contents == "-" || ls_receive_dt == "-")
					{
						CallMsgBoxInAjax("MSG_ERR_133");	//필수입력항목을 확인하세요
						lb_rslt = false;
					}
					else
					{
						//데이터정합성 체크
						if (!ValidationUtil.IsDateMask(ls_reg_dt) || 
							!ValidationUtil.IsDateMask(ls_receive_dt) ||
							!ValidationUtil.IsDateMask(ls_complete_dt) ||
							!ValidationUtil.IsDateMask(ls_real_complete_dt))
						{
							CallMsgBoxInAjax("MSG_ERR_082");	//잘못된 날짜형식입니다.올바른형식:YYYY-MM-DD
							lb_rslt = false;
						}
						
						if (!ValidationUtil.IsExistValueAtArray(la_cd, ls_div) || 
							!ValidationUtil.IsExistValueAtArray(la_cd, ls_status))
						{
							CallMsgBoxInAjax("MSG_ERR_116");	//잘못된 코드형식입니다
							lb_rslt = false;
						}
					}
				}
			}
			return lb_rslt;
		}

		//SetValue
		private string SetValue()
		{
			StringBuilder sb = new StringBuilder();
			sb.Append("<UPDMS>");

			//루프를 돌면서 저장할 데이터를 XML로 만듬
			for (int i = 0; i < GridView1.Rows.Count; i++)
			{
				GridViewRow row = GridView1.Rows[i];
				HtmlInputCheckBox cb = (HtmlInputCheckBox)row.FindControl("cb_check");

				if (cb.Checked)
				{
					string ls_prj_id			= ConversionUtil.DefaultValue(GridView1.Rows[i].Cells[2].Text);
					string ls_reg_dt			= ConversionUtil.DefaultValue(GridView1.Rows[i].Cells[3].Text);
					string ls_work_tp			= ConversionUtil.DefaultValue(GridView1.Rows[i].Cells[4].Text);
					string ls_pgm_nm			= ConversionUtil.DefaultValue(GridView1.Rows[i].Cells[5].Text);
					string ls_div				= ConversionUtil.DefaultValue(GridView1.Rows[i].Cells[6].Text, "AB001");
					string ls_no				= ConversionUtil.DefaultValue(GridView1.Rows[i].Cells[7].Text, "0");
					string ls_title				= ConversionUtil.DefaultValue(GridView1.Rows[i].Cells[8].Text);
					string ls_contents			= ConversionUtil.DefaultValue(GridView1.Rows[i].Cells[9].Text);
					string ls_handle_contents	= ConversionUtil.DefaultValue(GridView1.Rows[i].Cells[10].Text);
					string ls_concern_person	= ConversionUtil.DefaultValue(GridView1.Rows[i].Cells[11].Text);
					string ls_handle_time		= ConversionUtil.DefaultValue(GridView1.Rows[i].Cells[12].Text);
					string ls_receive_dt		= ConversionUtil.DefaultValue(GridView1.Rows[i].Cells[13].Text);
					string ls_complete_dt		= ConversionUtil.DefaultValue(GridView1.Rows[i].Cells[14].Text);
					string ls_real_complete_dt	= ConversionUtil.DefaultValue(GridView1.Rows[i].Cells[15].Text);
					string ls_status			= ConversionUtil.DefaultValue(GridView1.Rows[i].Cells[16].Text, "AA001");
					string ls_remark			= ConversionUtil.DefaultValue(GridView1.Rows[i].Cells[17].Text);

					sb.Append("<UPDMS_PRJ_PROGRESS_MGT>");
					sb.Append("<Prj_Id>" + ls_prj_id + "</Prj_Id>");
					sb.Append("<Reg_Dt>" + ls_reg_dt + "</Reg_Dt>");
					sb.Append("<Work_Tp><![CDATA[" + ls_work_tp + "]]></Work_Tp>");
					sb.Append("<Pgm_Nm><![CDATA[" + ls_pgm_nm + "]]></Pgm_Nm>");
					sb.Append("<Div>" + ls_div + "</Div>");
					sb.Append("<No>" + ls_no + "</No>");
					sb.Append("<Title><![CDATA[" + ls_title + "]]></Title>");
					sb.Append("<Contents><![CDATA[" + ls_contents + "]]></Contents>");
					sb.Append("<Handle_Contents><![CDATA[" + ls_handle_contents + "]]></Handle_Contents>");
					sb.Append("<Concern_Person><![CDATA[" + ls_concern_person + "]]></Concern_Person>");
					sb.Append("<Handle_Time>" + ls_handle_time + "</Handle_Time>");
					sb.Append("<Receive_Dt>" + ls_receive_dt + "</Receive_Dt>");
					sb.Append("<Complete_Dt>" + ls_complete_dt + "</Complete_Dt>");
					sb.Append("<Real_Complete_Dt>" + ls_real_complete_dt + "</Real_Complete_Dt>");
					sb.Append("<Status>" + ls_status + "</Status>");
					sb.Append("<Remark><![CDATA[" + ls_remark + "]]></Remark>");
					sb.Append("<Create_User>" + USER_ID + "</Create_User>");
					sb.Append("<Update_User>" + USER_ID + "</Update_User>");
					sb.Append("</UPDMS_PRJ_PROGRESS_MGT>");
				}
			}
			
			sb.Append("</UPDMS>");

			return sb.ToString();
		}

		#endregion

		#region Page_PreRender, ChangePageMode

		// Page_PreRender
		private void Page_PreRender(object sender, System.EventArgs e)
		{
			if (!Page.IsPostBack)
			{
				//접근권한 체크
				if (!access.CheckPgmAccessGrant(PID, USER_ID, ACCESS_LOG_INFO))
				{
					Response.Redirect(URL_NO_AUTHORITY_REDIRECT_POPUP);	//사용자의 권한은 요청하신 페이지를 볼 수 없습니다
				}
				//사용권한별 버튼처리
				PagePreRender.SetVisibleCtrl(this, access.CheckPgmUsingGrant(USER_DIV, PID), access.GetVisibleCtrl(PID));
			}
			ChangePageMode();
		}

		// ChangePageMode
		private void ChangePageMode()
		{
			switch (gs_page_mode)
			{
				case "":	// 처음 페이지로드시
					ibtn_search.Visible = FileUtil.IsFileExist(gs_source) ? true : false;
					ibtn_save.Visible = false;
					table_list_set.Visible = false;
					break;
				case "R":	// 검색버튼 클릭후 엑셀파일 있을때
					ibtn_search.Visible = true;
					ibtn_save.Visible = access.CheckPgmUsingGrant(USER_DIV, PID);
					table_list_set.Visible = true;
					break;
				case "N":	// 검색버튼 클릭후 엑셀파일 없을때
					ibtn_search.Visible = true;
					ibtn_save.Visible = false;
					table_list_set.Visible = false;
					break;
			}

			SetGridViewHeader(global.GetColumnListByPgmId(PID, LANG_SET));
		}

		#endregion

		#region File (UploadFile)

		//UploadFile
		private void UploadFile()
		{
			string ls_file_name = "";
			string upload_path = FILE_PATH_UPLOAD_EXCEL_BATCH;

			HttpFileCollection hfc = Request.Files;
			for (int i = 0; i < hfc.Count; i++)
			{
				HttpPostedFile hpf = hfc[i];
				if (hpf.ContentLength > 0)
				{
					ls_file_name = ls_file_name + Path.GetFileName(hpf.FileName);	//업로드시 선택한 파일명
					string ls_save_path = upload_path + ls_file_name; //저장경로

					//Prj4010b_template.xls만 업로드 가능
					if (ls_file_name == PID + "_template.xls")
					{
						//파일저장
						hpf.SaveAs(ls_save_path);
					}
					else
					{
						CallMsgBoxInAjax("MSG_ERR_196");	//템플릿 파일이 아닙니다
					}
				}
				else
				{
					CallMsgBoxInAjax("MSG_ERR_126");	//템플릿 파일이 없습니다
				}
			}
		}	

		#endregion

		#region GridView이벤트

		//RowDataBound
		protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
		{
			if (e.Row.RowType == DataControlRowType.DataRow)
			{
				//마우스올렸을 때
				e.Row.Attributes.Add("onMouseOver", GRID_ONMOUSEOVER_COLOR);
				e.Row.Attributes.Add("onMouseOut", GRID_ONMOUSEOUT_COLOR);

				//번호
				e.Row.Cells[1].Text = (e.Row.RowIndex + 1).ToString();
			}
		}

		#endregion

		#region 버튼이벤트

		//검색
		protected void ibtn_search_Click(object sender, EventArgs e)
		{
			SearchProcess();
		}

		//저장
		protected void ibtn_save_Click(object sender, EventArgs e)
		{
			if (CheckData())
			{
				InsertProcess();
			}
		}

		//업로드
		protected void ibtn_upload_Click(object sender, EventArgs e)
		{
			UploadFile();
		}
		

		#endregion

	}
}
